package com.cheneyjoo.view;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cheneyjoo.base.Menu;
import com.cheneyjoo.model.RequestMessage;
import com.cheneyjoo.util.CheneyScanner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.*;

public class UserMenu extends Menu {
    public UserMenu() {
    }

    public UserMenu(Socket socket, PrintStream out, BufferedReader in) {
        super.setSocket(socket);
        super.setOut(out);
        super.setIn(in);
    }

    @Override
    public void menu() throws IOException {
        boolean isOnline = true;
        while (isOnline) {
            System.out.println("------------------------------------------");
            System.out.println("--用户管理");
            System.out.println("      [1]修改密码");
            System.out.println("--考试管理");
            System.out.print("      [2]开始考试");
            System.out.println("      [3]查看成绩");
            System.out.println(" [0]退出系统");
            System.out.println("请选择对应的功能编码：");
            System.out.println("------------------------------------------");
            String menu = CheneyScanner.reader.readLine();
            switch (menu) {
                case "1":
                    updatePwd();
                    break;
                case "2":
                    startExam();
                    break;
                case "3":
                    getExamAnswer();
                    break;
                default:
                    System.out.println("bye");
                    super.getOut().println("bye");
                    isOnline = false;
                    String readLine = super.getIn().readLine();
                    if ("*server close*".equals(readLine)) {
                        super.getIn().close();
                        super.getOut().close();
                    }
            }
        }
    }

    /**
     * 修改密码
     *
     * @throws IOException
     */
    private void updatePwd() throws IOException {
        System.out.println("请输入账户旧密码：");
        String oldPwd = CheneyScanner.reader.readLine();
        String newPwd = "", confirmNewPwd = "";
        while (true) {
            System.out.println("请输入账户新密码：");
            newPwd = CheneyScanner.reader.readLine();
            System.out.println("请确认账户新密码：");
            confirmNewPwd = CheneyScanner.reader.readLine();
            if (newPwd.equals(confirmNewPwd)) {
                break;
            }
            System.out.println("两次密码输入不一致，重新输入！");
        }
        Map<String, Object> para = new LinkedHashMap<>();
        para.put("id", Integer.parseInt(super.getUserMap().get("id")));
        para.put("oldPwd", oldPwd);
        para.put("newPwd", newPwd);
        RequestMessage rm = new RequestMessage("user", "updatePwd", para);
        JSONObject result = getResponseResult(rm);
        if (result.getString("code").equals("200")) {
            System.out.println("修改成功");
            ;
        } else {
            System.out.println(result.getString("message"));
            ;
        }
    }

    /**
     * 开始考试
     */
    private void startExam() throws IOException {
        Map<String, Object> body = new HashMap<>();
        body.put("body", 1);
        RequestMessage rm = new RequestMessage("exam", "getExamByStatus", body);
        JSONObject result = getResponseResult(rm);
        Object content = result.get("content");
        if (content.getClass().equals(JSONArray.class)) {
            JSONArray exams = (JSONArray) content;
            if (exams.size() == 0) {
                System.out.println("暂无可进行的考试！");
                return;
            } else {
                System.out.println("ID\t试卷名称\t科目\t状态");
                for (Object exam : exams) {
                    JSONObject o = (JSONObject) exam;
                    System.out.println(o.get("id") + "\t" + o.get("examName") + "\t" + o.get("categoryName") + "\t" + (o.get("status").toString().equals("0") ? "未发布" : "已发布"));
                }
            }
        }
        int ExamID = 0;
        while (true) {
            System.out.println("请输入要进行考试的试卷ID");
            String examID = CheneyScanner.reader.readLine();
            try {
                ExamID = Integer.parseInt(examID);
                break;
            } catch (NumberFormatException e) {
                System.out.println("试卷ID格式输入有误，请重新输入！！");
            }
        }
        body = new HashMap<>();
        body.put("body", ExamID);
        rm = new RequestMessage("exam", "getExamById", body);
        result = getResponseResult(rm);
        if (!result.get("code").toString().equals("200")) {
            System.out.println("输入的试卷未找到！");
            return;
        } else {
            JSONObject examContent = result.getJSONObject("content");
            String examName = examContent.getString("examName");
            String categoryName = examContent.getString("categoryName");
            JSONArray questions = examContent.getJSONArray("questions");
            JSONObject userExamAnswer = new JSONObject();
            System.out.println("您正在进行的考试为：" + examName);
            System.out.println("考试科目为：" + categoryName);
            System.out.println("----------------接下来是答题时间-------------------------");
            List<Object> userAnswers = new ArrayList<>();
            for (var question : questions) {
                JSONObject userAnswer = new JSONObject();
                JSONObject getQuestion = JSONObject.parseObject(question.toString());
                userAnswer.put("question", getQuestion);
                System.out.println(getQuestion.getString("name"));
                JSONArray answers = getQuestion.getJSONArray("answers");
                List<String> optionList = new ArrayList<>();
                for (var answer : answers) {
                    JSONObject getAnswer = JSONObject.parseObject(answer.toString());
                    optionList.add(getAnswer.getString("option"));
                    System.out.print(getAnswer.getString("option")+":"+getAnswer.getString("content") + "\t");
                }
                System.out.println();
                while (true) {
                    System.out.println("请选择正确答案：");
                    String rightOption = CheneyScanner.reader.readLine();
                    long count = optionList.stream().filter(s -> s.equals(rightOption)).count();
                    if (count > 0) {
                        userAnswer.put("userAnswer", rightOption);
                        break;
                    }
                    System.out.println("未匹配到对应的选项，请重新输入");
                }
                userAnswers.add(userAnswer);
            }
            userExamAnswer.put("userID", super.getUserMap().get("id"));
            userExamAnswer.put("userName", super.getUserMap().get("name"));
            userExamAnswer.put("examID", ExamID);
            userExamAnswer.put("examName", examName);
            userExamAnswer.put("categoryName", categoryName);
            userExamAnswer.put("questionAnswers", userAnswers);
            body = new HashMap<>();
            body.put("body", JSON.toJSONString(userExamAnswer));
            rm = new RequestMessage("userexamanswer", "addUserExamAnswer", body);
            result = getResponseResult(rm);
            System.out.println("考试结束");
        }
    }

    /**
     * 查看成绩
     * @throws IOException
     */
    private void getExamAnswer()throws IOException{
        Map<String, Object> body = new HashMap<>();
        body.put("body",Integer.parseInt(super.getUserMap().get("id")));
        RequestMessage rm = new RequestMessage("userexamanswer", "getUserExamAnswers", body);
        JSONObject result = getResponseResult(rm);
        Object content = result.get("content");
        if (content.getClass().equals(JSONArray.class)){
            JSONArray exams = (JSONArray) content;
            if (exams.size() == 0) {
                System.out.println("暂无考试成绩！");
                return;
            } else {
                System.out.println("试卷名称\t科目\t成绩");
                for (Object exam : exams) {
                    JSONObject o = (JSONObject) exam;
                    System.out.println(o.get("examName") + "\t" + o.get("categoryName") + "\t" + o.get("sumScore").toString());
                }
            }
        }
    }
    /**
     * 发送数据并等待回复数据
     *
     * @param rm
     * @return
     * @throws IOException
     */
    private JSONObject getResponseResult(RequestMessage rm) throws IOException {
        super.getOut().println(JSON.toJSONString(rm));
        String readLine = super.getIn().readLine();
        return JSON.parseObject(readLine);
    }
}
